#!BPY

"""
Name: 'Dwarf3d Armature (.dwarfarm)'
Blender: 248
Group: 'Armature'
Tooltip: 'Exports an armature into an OBJ-like file'
"""

import Blender
from Blender import sys, Window, Mathutils
from Blender.Mathutils import *

import bpy

activeObj = bpy.data.scenes.active.objects.active

def getRootBone(arm):
	for bone in arm.bones.values():
		if bone.parent == None:
			return bone
		else:
			continue
			
def createBoneStack(bone):
	boneStack = [bone]
	for bone in boneStack:
		for child in bone.children:
			boneStack.append(child)
	return boneStack

def writeBone(bone, file):
	if bone.hasParent():
		file.write("b " + bone.name + " " + bone.parent.name + "\n")
	else:
		file.write("r " + bone.name + "\n")
	
	matrix = Matrix(bone.matrix["BONESPACE"])
	matrix.resize4x4()
	
	if bone.hasParent() == False:
		matrix = RotationMatrix(-90, 4, "x") * matrix
		head = bone.head["ARMATURESPACE"]
		matrix[3][0] = head.x
		matrix[3][1] = head.z
		matrix[3][2] = head.y
		matrix[3][3] = 1;
		
	file.write("l %f\n" % (bone.tail["BONESPACE"].length))
	
	file.write("m 0 %f %f %f %f\n" % tuple(matrix[0]))
	file.write("m 1 %f %f %f %f\n" % tuple(matrix[1]))
	file.write("m 2 %f %f %f %f\n" % tuple(matrix[2]))
	file.write("m 3 %f %f %f %f\n" % tuple(matrix[3]))

def exportArmature(filename):
	arm = bpy.data.armatures[activeObj.name]
	file = open(filename, "w")
	file.write("# Created with Mercury's Armature Export script\n\n")
	file.write("a " + arm.name + "\n\n")
	root = getRootBone(arm)
	boneStack = createBoneStack(root)
	for bone in boneStack:
		writeBone(bone, file)
		file.write("\n")
	file.close()
	
if activeObj == None:
	print("No armature is currently selected.")
elif activeObj.type != "Armature":
	print("The selected object is not an armature.")
else:
	Window.FileSelector(exportArmature, 'Export Armature', activeObj.name + ".dwarfarm")
	